package com.cws4cloud.cws.mall.xsm.util;

/**
 *
 * 该类由新商盟提供
 * Created by david on 15/12/11.
 */


import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Random;

public class OrgEncode {

    /**
     * 加密
     * @param $txt
     * @return
     */
    public static String incode(String $txt){
        String $key = "xinshangmengst2013";
        String $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_";
        Random r = new Random();
        int $nh = r.nextInt(64);
        char chars_aray[] = $chars.toCharArray();
        char $ch = chars_aray[$nh];
        String $mdKey = md5 ( $key + $ch );
        $mdKey = $mdKey.substring($nh % 8, $nh % 8+$nh % 8 + 7 );
        $txt = Base64.encodeBytes($txt.getBytes());
        $txt = $txt.replace("\n", "");
        $txt = $txt.replace("\r", "");
        char $txt_array[] = $txt.toCharArray();
        char $mdKey_array[] = $mdKey.toCharArray();
        String $tmp = "";
        int $i = 0;
        int $j = 0;
        int $k = 0;
        for($i = 0; $i < $txt.length(); $i ++) {
            $k = $k == $mdKey.length() ? 0 : $k;
            $j = ($nh + $chars.indexOf($txt_array [$i]) + (int)( $mdKey_array [$k ++] )) % 64;
            $tmp = $tmp + chars_aray[$j];
        }
        return $ch + $tmp;
    }

    /**
     * md5
     * @return String
     */
    public static String md5(String plainText){
        if(plainText == null)
            plainText = "";
        byte[] temp = plainText.getBytes();
        MessageDigest md;
        // 返回结果
        StringBuffer buffer = new StringBuffer();
        try {
            // 进行MD5散列
            md = MessageDigest.getInstance("md5");
            md.update(temp);
            temp = md.digest();
            // 将散列的结果转换为Hex字符串
            int i = 0;
            for (int offset = 0; offset < temp.length; offset++) {
                i = temp[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buffer.append("0");
                buffer.append(Integer.toHexString(i));
            }
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        // 返回
        return buffer.toString();
    }
    public static void main(String args[]){
//        String orgCode = "a23c512613e2b0a29f4aa3b9c0b5731b";
//        String s = incode(orgCode);
//        System.out.println("s--:"+s);
//        String e = OrgDecode.decode(s);
//        System.out.println("e--:"+e);
    }
}
